import Vue from 'vue'
import axios from 'axios'
import store from '@/store'
import { mapActions } from 'vuex'
import { VueAxios } from './axios'
import { Modal, notification } from 'ant-design-vue'
import { ACCESS_TOKEN, TENANT_ID } from '@/store/mutation-types'
import router from '@/router'

/**
 * 【指定 axios的 baseURL】
 * 如果手工指定 baseURL: '/cnForm-boot'
 * 则映射后端域名，通过 vue.config.js
 * @type {*|string}
 */
let apiBaseUrl = window._CONFIG['domainUrl']
// let apiBaseUrl = '/recover';

// 创建 axios 实例
const service = axios.create({
  //baseURL: '/cnForm-boot',
  baseURL: apiBaseUrl, // api base_url
  timeout: 1800000 // 请求超时时间
})

const err = (error) => {
  if (error.response) {
    let that = this
    let data = error.response.data
    const token = Vue.ls.get(ACCESS_TOKEN)
    console.log('------异常响应------', token)
    console.log('------异常响应------', error.response.status)
    switch (error.response.status) {
      case 403:
        notification.error({ message: '系统提示', description: '拒绝访问', duration: 4 })
        break
      case 500:
        //notification.error({ message: '系统提示', description:'Token失效，请重新登录!',duration: 4})
        if (token && data.message == 'Token失效，请重新登录') {
          // update-begin- --- author:scott ------ date:20190225 ---- for:Token失效采用弹框模式，不直接跳转----
          // store.dispatch('Logout').then(() => {
          //     window.location.reload()
          // })
          Modal.error({
            title: '登录已过期',
            content: '很抱歉，登录已过期，请重新登录',
            okText: '重新登录',
            mask: false,
            onOk: () => {
              store.dispatch('Logout').then(() => {
                Vue.ls.remove(ACCESS_TOKEN)
                try {
                  let path = that.$route.path
                  if (path.indexOf('/user/login') == -1) {
                    window.location.reload()
                  }
                } catch (e) {
                  window.location.reload()
                }
              })
            }
          })
          // update-end- --- author:scott ------ date:20190225 ---- for:Token失效采用弹框模式，不直接跳转----
        }
        break
      case 404:
        notification.error({ message: '系统提示', description: '很抱歉，资源未找到!', duration: 4 })
        break
      case 504:
        notification.error({ message: '系统提示', description: '网络超时' })
        break
      case 401:
        if(!data){
          handleWaitQueue(error.response)
        }else {
          let code =data.code ;
          if (code == 401 ){
            notification.error({ message: '系统提示', description: '未授权，请重新登录', duration: 4 })
          }
        }
        break
      default:
        notification.error({
          message: '系统提示',
          description: data.message,
          duration: 4
        })
        break
    }
  }
 if(error.response.code!=401){
   return Promise.reject(error)
 }else {

 }



}
// request interceptor
service.interceptors.request.use(config => {
  const token = Vue.ls.get(ACCESS_TOKEN)
  console.log(config.url.indexOf('/oauth/token'))
  if (token) {
    if (config.url.indexOf('/oauth/token') != -1) {

    } else {
      config.headers['Authorization'] = `Bearer ${token.access_token}`  // 让每个请求携带自定义 token 请根据实际情况自行修改
    }
  }

  if (!/^[http|https]+\:\/\//.test(config.url)) {
    config.url = window._CONFIG['domianURL'] + config.url
  }
  // console.log(`当前请求的config`,config)
  // console.log(`当前请求的url：'${config.url}'`)
  // console.log(`url是否以'http://'开头：${/^[http|https]\:\/\//.test(config.url)}`)
  // console.log(`当前发出请求的模块：'${router.app.$route.meta.contextPath}'`)
  // const path = /(.*[\/].*){4,}/
  // const module = /^(?!\b(mdm|sfa)\b)/
  // if(!/(^(?!(\bmdm\b|\bsfa\b|\btpm\b)))((.*[\/].*){3,})/.test(config.url)){
  //   config.url =  '/mdm/' + config.url
  // }
  // if(!/(\bmdm\b)/g.test(config.url)){
  //   config.url =  '/huishou/' + config.url
  // }
  //update-begin-author:taoyan date:2020707 for:多租户
  // let tenantid = Vue.ls.get(TENANT_ID)
  // if (!tenantid) {
  //   tenantid = 0;
  // }
  // config.headers[ 'tenant_id' ] = tenantid
  // //update-end-author:taoyan date:2020707 for:多租户
  // if(config.method=='get'){
  //   if(config.url.indexOf("sys/dict/getDictItems")<0){
  //     config.params = {
  //       _t: Date.parse(new Date())/1000,
  //       ...config.params
  //     }
  //   }
  // }
  return config
}, (error) => {
  return Promise.reject(error)
})
let refreshing = false,// 正在刷新标识，避免重复刷新
  waitQueue = [] // 请求等待队列
const handleWaitQueue = (res) =>{
  const tokenOne = Vue.ls.get(ACCESS_TOKEN)
  const code = res.status || 200
  if (code == 401) {
    const config = res.config
    if (refreshing == false) {
      refreshing = true
      const refreshToken = {
        saasid: store.state.app.pageConfig.saasid,
        grant_type: 'refresh_token',
        client_id: 'client-app',
        client_secret: '123456',
        refresh_token: tokenOne.refresh_token
      }
      return store.dispatch('Login', refreshToken).then((token) => {
        config.headers['Authorization'] = `Bearer ${token.access_token}`
        config.baseURL = '' // 请求重试时，url已包含baseURL
        waitQueue.forEach(callback => callback(token)) // 已刷新token，所有队列中的请求重试
        waitQueue = []
        return service(config)
      }).catch(() => { // refresh_token也过期，直接跳转登录页面重新登录
        Modal.error({
          title: '登录已过期',
          content: '很抱歉，登录已过期，请重新登录',
          okText: '重新登录',
          mask: false,
          onOk: () => {
            store.dispatch('Logout').then(() => {
              Vue.ls.remove(ACCESS_TOKEN)
              try {
                let path = that.$route.path
                if (path.indexOf('/user/login') == -1) {
                  window.location.reload()
                }
              } catch (e) {
                window.location.reload()
              }
            })
          }
        })
      }).finally(()=>{
        refreshing = false
      })
    } else {
      // 正在刷新token，返回未执行resolve的Promise,刷新token执行回调
      return new Promise((resolve => {
        waitQueue.push((token) => {
          config.headers['Authorization'] = `Bearer ${token.access_token}`
          config.baseURL = '' // 请求重试时，url已包含baseURL
          resolve(service(config))
        })
      }))
    }
  }
}

let subscribers = [];
function onAccessTokenFetched() {
  subscribers.forEach((callback)=>{
    callback();
  })
  subscribers = [];
}

function addSubscriber(callback) {
  subscribers.push(callback)
}

// response interceptor
service.interceptors.response.use((response) => {
  handleWaitQueue(response)
  return response.data
}, err)

const installer = {
  vm: {},
  install(Vue, router = {}) {
    Vue.use(VueAxios, router, service)
  }
}

export {
  installer as VueAxios,
  service as axios
}
